package com.software.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.software.bean.CategoryBean;
import com.software.dto.CategoryDto;
import com.software.dto.EditCategoryDto;
import com.software.dto.MidIconDto;
import com.software.dto.ThirdCategoryDto;
import com.software.mapper.CategoryMapper;
import com.software.service.CategoryService;
import com.software.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyj
 * @since 2024-03-07
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryBean> implements CategoryService {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CategoryMapper categoryMapper;


    // 小程序 主页中部图片
    @Override
    public List<CategoryBean> queryMidIconInHomePage() {
        List<CategoryBean> list = categoryMapper.queryMidIconInHomePage();
        return list;
    }

    //后台主页中部图标管理 + 分页
    @Override
    public IPage<CategoryBean> queryMidIconPagination(Integer pageNum, Integer pageSize) {
        AssertUtil.isTrue(pageNum == 0, "参数异常1");
        AssertUtil.isTrue(pageSize == 0, "参数异常2");

        Page<CategoryBean> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        IPage<CategoryBean> iPage = categoryMapper.queryMidIconPagination(page);
        return iPage;
    }

    //添加中部图标 等价于添加一级分类
    @Override
    public int addMidIcon(MidIconDto midIconDto) {

        AssertUtil.isTrue(midIconDto.getLevel() != 1, "等级必须为1 ");
        AssertUtil.isTrue(StringUtils.isEmpty(midIconDto.getName()), "图标名称不能为空");
        AssertUtil.isTrue(midIconDto.getFile() == null, "图片不能空");
        // 判断是否重复添加
        Integer existsCount = categoryMapper.queryIconName(midIconDto.getName());
        AssertUtil.isTrue(existsCount != 0, "重复添加");
        CategoryBean categoryBean = getCateBean(midIconDto.getName(), midIconDto.getLevel());
        // 图标图片操作
        String iconUrl = saveIcon(midIconDto.getFile());
        categoryBean.setIconUrl(iconUrl);
        int insert = categoryMapper.insert(categoryBean);
        return insert;
    }


    private CategoryBean getCateBean(String midIconName, Integer level) {
        CategoryBean categoryBean = new CategoryBean();
        categoryBean.setCreateTime(new Date());
        categoryBean.setUpdateTime(new Date());
        categoryBean.setName(midIconName);
        categoryBean.setStatus(1);
        categoryBean.setIsHome(1);
        categoryBean.setParentId(0);
        categoryBean.setLevel(level);
        return categoryBean;
    }

    // saveIcon 方法 返回imgUrl
    private String saveIcon(MultipartFile multipartFile) {
        String realPath = "E:/img";
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String imgUrl = "http://localhost:8082/file/" + fileName + ".png";
        String filePath = realPath + "/" + fileName + ".png";
        MultipartFile file = multipartFile;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imgUrl;

    }


    /**
     * @description:
     * @author: wyj
     * @date: 2024/3/9 22:29
     * @param:删除中部图标逻辑删除ishome=0不在中部显示，但是存在子分类不能直接删除
     * @return:
     */
    @Override
    public int deleteMidIcon(Integer id) {
        AssertUtil.isTrue(id == 0 || id == null, "参数异常");
        CategoryBean categoryBean = categoryMapper.selectById(id);
        AssertUtil.isTrue(categoryBean == null, "返回值异常1");
        categoryBean.setIsHome(0);
        int i = categoryMapper.updateById(categoryBean);
        System.out.println("iii" + i);
        AssertUtil.isTrue(i == 0, "返回值异常2");
        return i;
    }

    // 小程序分类 三级列表
    @Override
    public List<Map<String, Object>> allCategory() {
        // 取 全部分类数据
        List<Map<String, Object>> mapList = categoryService.listMaps();
        AssertUtil.isTrue(mapList.size() == 0, "分类信息异常");
        // 创建一个空的集合
        List<Map<String, Object>> allMenu = new ArrayList<>();
        //  加进去
        for (Map<String, Object> map : mapList) {
            allMenu.add(map);
        }
        // 添加一级分类
        List<Map<String, Object>> firstMenu = new ArrayList<>();
        for (Map<String, Object> nav : allMenu) {
            Integer pid = (Integer) nav.get("parentId");
            String parentId = String.valueOf(pid);
            // System.out.println(parentId );
            if (parentId.equals("0")) {
                firstMenu.add(nav);
            }
        }
        // 判断是否有二级分类 有二级分类就添加
        for (Map<String, Object> nav : firstMenu) {
            String id = String.valueOf(nav.get("id"));
            List<Map<String, Object>> childList = getChild(id, allMenu);
            nav.put("children", childList);
        }
        return firstMenu;
    }

    //添加二级分类的时候的select 下拉列表
    @Override
    public List<Map<String, Integer>> queryAllFirstCategory() {
        List<Map<String, Integer>> maps = categoryMapper.queryAllFirstCategory();
        AssertUtil.isTrue(maps.size() == 0, "返回值异常");
        return maps;
    }

    // 添加二级分类的方法
    private List<Map<String, Object>> getChild(String id, List<Map<String, Object>> allMenu) {
        List<Map<String, Object>> childList = new ArrayList<>();
        for (Map<String, Object> nav : allMenu) {
            String pid = String.valueOf(nav.get("parentId"));
            if (id.equals(pid)) {
                // 添加二级分类
                childList.add(nav);
            }
        }
        for (Map<String, Object> nav : childList) {
            String tempId = String.valueOf(nav.get("id"));
            // 如果有二级分类下有三级分类 递归调用添加三级分类
            nav.put("children", getChild(tempId, allMenu));
        }
        if (childList.size() == 0) {
            // 往下没有分类了 递归出口
            return new ArrayList<>();
        }
        return childList;
    }


    //后台 添加二级分类
    @Override
    public Integer addSecondCategory(CategoryDto categoryDto) {
        AssertUtil.isTrue(categoryDto.getParentId() == 0, "父分类异常");
        AssertUtil.isTrue(StringUtils.isEmpty(categoryDto.getName()), "二级分类名不能为空");
        AssertUtil.isTrue(categoryDto.getLevel() != 2, "等级异常");

        //查父类别
        CategoryBean parentCategory = categoryService.getById(categoryDto.getParentId());
        AssertUtil.isTrue(parentCategory.getId() == null || parentCategory.getId() == 0, "返回值异常");
        // 初始化类
        CategoryBean categoryBean = new CategoryBean();
        categoryBean.setName(categoryDto.getName());
        categoryBean.setLevel(categoryDto.getLevel());
        categoryBean.setParentId(categoryDto.getParentId());
        categoryBean.setStatus(1);
        categoryBean.setIconUrl(null);
        categoryBean.setUpdateTime(new Date());
        categoryBean.setCreateTime(new Date());
        categoryBean.setIsHome(0);
        // 添加
        boolean save = categoryService.save(categoryBean);
        return save == true ? 1 : 0;
    }

    // 小程序 三级分类
    @Override
    public List<Map<String, Object>> getCategoryByFront() {
        List<Map<String, Object>> mapList = categoryMapper.getCategoryByFront();
        AssertUtil.isTrue(mapList.size() == 0, "分类信息返回异常");
        List<Map<String, Object>> firstMenu = new ArrayList<>();
        for (Map<String, Object> nav : mapList) {
            String pid = String.valueOf(nav.get("parentId"));
            if ("0".equals(pid)) {
                // 添加一级分类
                firstMenu.add(nav);
            }
        }
        // 判断是否有二级分类
        for (Map<String, Object> childrenNav : firstMenu) {
            String id = String.valueOf(childrenNav.get("id"));
            List<Map<String, Object>> childrenList = getChild(id, mapList);
            childrenNav.put("children", childrenList);
        }

        for (Map<String, Object> nav : firstMenu) {
            System.out.println(nav);
        }
        return firstMenu;
    }

    // 删除分类
    @Override
    public Integer deleteCategory(Integer id) {
        AssertUtil.isTrue(id == null, "参数异常");
        CategoryBean categoryBean = categoryMapper.selectById(id);
        AssertUtil.isTrue(categoryBean == null, "返回值异常");
        if (!categoryBean.getIconUrl().isEmpty()) {
            // 删除图片
            Boolean result = deleteIcon(categoryBean.getIconUrl());
            AssertUtil.isTrue(result != true, "文件操作异常");
        }

        // 删除数据库
        int i = categoryMapper.deleteById(id);
        return i == 1 ? 1 : 0;
    }

    // 添加三级分类
    @Override
    public Integer addThirdCategory(ThirdCategoryDto thirdCategoryDto) {
        // 参数校验
        AssertUtil.isTrue(thirdCategoryDto.getFile() == null, "图标不能为空");
        AssertUtil.isTrue(thirdCategoryDto.getLevel() != 3, "等级必须为3");
        AssertUtil.isTrue(StringUtils.isEmpty(thirdCategoryDto.getName()), "分类名称不能为空");
        AssertUtil.isTrue(thirdCategoryDto.getParentId() == null, "父级分类异常");
        // 判断父级分类是否有效
        CategoryBean categoryBean = categoryMapper.selectById(thirdCategoryDto.getParentId());
        AssertUtil.isTrue(categoryBean == null, "返回值异常");

        CategoryBean insert = new CategoryBean();
        insert.setLevel(thirdCategoryDto.getLevel());
        insert.setName(thirdCategoryDto.getName());
        insert.setCreateTime(new Date());
        insert.setIsHome(0);
        insert.setParentId(thirdCategoryDto.getParentId());
        insert.setStatus(1);
        insert.setUpdateTime(new Date());
        insert.setIconUrl(saveIcon(thirdCategoryDto.getFile()));

        int i = categoryMapper.insert(insert);
        return i == 1 ? 1 : 0;
    }

    // 修改分类 根据id 获取一行数据
    @Override
    public CategoryBean getCategoryById(Integer id) {
        AssertUtil.isTrue(id == null, "参数异常");
        CategoryBean categoryBean = categoryMapper.selectById(id);
        AssertUtil.isTrue(categoryBean == null, "返回值异常");

        return categoryBean;
    }

    // 更新分类
    @Override
    public Integer updateCategory(EditCategoryDto editCategoryDto) {
        String iconUrl = null;
        AssertUtil.isTrue(editCategoryDto.getId() == null, "参数异常");
        AssertUtil.isTrue(StringUtils.isEmpty(editCategoryDto.getName()), "参数异常");
        AssertUtil.isTrue(editCategoryDto.getIsHome() == null, "参数异常");
        if (editCategoryDto.getIsChangeIcon() == true) {
            // 校验文件
            AssertUtil.isTrue(editCategoryDto.getFile() == null, "文件异常");
        }
        // 根据id查记录
        CategoryBean result = categoryMapper.selectById(editCategoryDto.getId());
        AssertUtil.isTrue(result == null, "返回值异常");

        // 先删除文件
        if (editCategoryDto.getIsChangeIcon() == true) {
            Boolean deleteIcon = deleteIcon(result.getIconUrl());
            AssertUtil.isTrue(deleteIcon == false, "文件操作异常");
            // 在添加文件
            iconUrl = saveIcon(editCategoryDto.getFile());
        }
        // 更新
        CategoryBean update = new CategoryBean();
        update.setIsHome(editCategoryDto.getIsHome());
        update.setId(editCategoryDto.getId());
        update.setUpdateTime(new Date());
        update.setName(editCategoryDto.getName());
        update.setIconUrl(iconUrl);

        int i = categoryMapper.updateById(update);
        return i == 1 ? 1 : 0;
    }

    /**
     * @description:前端小程序发布的分类选择器
     * @author: wyj
     * @date: 2024/3/28 14:49
     * @param:
     * @return:返回时所有一级分类
     */
    @Override
    public List<Map<String, Integer>> getCategoryForRelease() {
        List<Map<String, Integer>> maps = categoryMapper.selectCategoryLevelOne();
        AssertUtil.isTrue(maps.size() == 0, "返回值异常");
        return maps;
    }

    // 删除图片
    private Boolean deleteIcon(String iconUrl) {
        // 从url 最后一个斜杠往后截取 拼接filePath
        String str = iconUrl.substring(iconUrl.lastIndexOf("/") + 1);

        String realPath = "E:/img";
        String filePath = realPath + "/" + str;
        File file = new File(filePath);
        if (file.exists()) {
            boolean delete = file.delete();
            AssertUtil.isTrue(delete == false, "文件操作异常");
        }

        return true;
    }


}
